from custom.handlers.basehandler import BaseRequestHandler
from models.tables import UserModel
from sqlalchemy.orm.exc import NoResultFound


class LoginHandler(BaseRequestHandler):
    def post(self):
        username = self.get_argument('username')
        password = self.get_argument('password')
        try:
            user = self.db.query(UserModel).filter_by(username=username, password=password).one()
        except NoResultFound as e:
            user = None
        if user:
            self.success(200, 'success', self.json_encoder.encode(user))
        else:
            self.success(201, '用户名或密码错误', None)


class IndexListHandler(BaseRequestHandler):
    def get(self, *args, **kwargs):
        users = self.db.query(UserModel).all()
        self.success(200, 'success', {'users': self.json_encoder.encode(users)})


class IndexDetailHandler(BaseRequestHandler):
    def get(self, *args, **kwargs):
        self.success(200, 'success', {'name': 'tom', 'age': 25})


class SearchWbHandler(BaseRequestHandler):
    def post(self, *args, **kwargs):
        keyword = self.get_argument('keyword')
        search_type = self.get_argument('type')
        print('keyword', keyword)
        result = self.weibo_spider.search_user(keyword)
        self.success(200, 'success', result)
